package bank.jms;

import java.io.IOException;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;

import bank.InactiveException;
import bank.OverdrawException;
import bank.transport.Answer;
import bank.transport.Request;

/**
 * Handels the connection with the bank server. It sends the requests to the
 * server and forwards the answer objects.
 * 
 * @author Roland
 */
public class JMSBankHandler implements Runnable {

	/**
	 * Sender object for sending messages to the queue.
	 */
	public QueueSender sender;
	/**
	 * Reader object for receiving messages from he queue.
	 */
	public QueueReceiver receiver;
	/**
	 * Session object for the active mq session.
	 */
	public QueueSession session;
	/**
	 * Queue instance of the queue to write requests.
	 */
	public Queue queue;
	/**
	 * Temporary Receive Queue for each Client
	 */
	public Queue receiveQueue;

	/**
	 * Create a new SocketBankHandler object which manages the connection with
	 * the server.
	 * 
	 * @param s
	 * @throws IOException
	 */
	public JMSBankHandler(QueueSession s, Queue q) throws JMSException {
		this.session = s;
		this.queue = q;
	}

	/**
	 * Sends requests to the server forwards the answer object
	 * 
	 * @param req Request for the server
	 * @return answer object
	 * @throws IOException
	 */
	public Answer sendRequest(Request req) throws IOException {
		try {

			ObjectMessage request = session.createObjectMessage();
			request.setObject(req);
			request.setJMSReplyTo(receiveQueue);

			sender.send(request);

			ObjectMessage response = (ObjectMessage) receiver.receive();
			return (Answer) response.getObject();

		} catch (JMSException ex) {

		} catch (ClassCastException ex) {
			System.err.println("Probably a wrong request has been sent.");
		}
		return null;
	}
}
